package com.shelpe.services.lexicon.service.tag;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import com.shelpe.services.lexicon.entity.KeywordRecommend;
import com.shelpe.services.lexicon.entity.KeywordTag;
import com.shelpe.services.lexicon.entity.Scope;
import com.shelpe.services.lexicon.entity.WordInsightMetric;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
/**
 * 飙升包规则
 * @author Otis
 *
 */
public class PromoteRecommendTagRule implements RecommendTagRule {
	
	@Override
	public KeywordTag tag(KeywordRecommend word,TagRuleContext context) {
		KeywordTag tag = null;
		
		boolean satisfied = false;
		log.debug("start find past 4 query global metric");
		List<WordInsightMetric> kms = context.getLast4roundMetrics();
		log.debug("end find past 4 query global metric");
		
		int avePastIn7 = 0;
		int avePast14 = 0;
		if(kms != null){
			Date today = DateUtils.truncate(new Date(), Calendar.DATE);
			Date ago6 = DateUtils.addDays(today, -7);
			Date ago12 = DateUtils.addDays(today, -13);
			for(WordInsightMetric km:kms){
				if(this.isBetween(km.getScope(), ago6, today)){
					avePastIn7 = avePastIn7 > 0?((avePastIn7 + km.getMetric().getImpression())/2):km.getMetric().getImpression();
				}else{
					if(this.isBetween(km.getScope(), ago12, today)){
						avePast14 = avePast14 > 0?((avePast14 + km.getMetric().getImpression())/2):km.getMetric().getImpression();
					}
				}
			}
			if(avePastIn7 > 0 && avePast14 > 0){
				int promote = (avePastIn7 - avePast14) * 100 / avePastIn7;
				if(promote > 30){
					satisfied = true;
				}
			}
		}
		
		if(satisfied){
			tag = new KeywordTag();
			tag.setTagID(2);
			tag.setTagName("promote");
		}
		return tag;
	}

	
	private boolean isBetween(Scope scope, Date start, Date end){
		return !start.after(DateUtils.truncate(scope.getStartTime(), Calendar.DATE)) && !end.before(DateUtils.truncate(scope.getEndTime(), Calendar.DATE));
	}
	
}
